
#include <QSqlQuery>
#include <QSqlRecord>
#include <QVariant>
#include <QMessageBox>
#include "LocationDao.h"


MoneyLocation searchForLocation(QList<MoneyLocation> listMoneyLocation, int idLocation)
{
    foreach (MoneyLocation location, listMoneyLocation) {
        if (location.getId() == idLocation)
            return location;
    }

    return MoneyLocation();
}

QList<MoneyLocation> getAllMoneyLocation(QString user_prefix)
{

    QString strQuery = " SELECT id_location, name, description as id_location, name, description FROM ";
    strQuery = strQuery + user_prefix + "_location ";

    QSqlQuery query(strQuery);
    QList<MoneyLocation> listMoneyLocation;
    query.exec();
    while (query.next()) {
        MoneyLocation moneyLocation(query.value(query.record().indexOf("id_location")).toInt(),
                                    query.value(query.record().indexOf("name")).toString(),
                                    query.value(query.record().indexOf("description")).toString());
        listMoneyLocation.append(moneyLocation);
    }

    return listMoneyLocation;
}

bool deleteMoneyLocation(MoneyLocation* location, QString user_prefix)
{
    if (!location)
        return false;

    QString strQuery = " DELETE FROM ";
    strQuery = strQuery + user_prefix + "_location "
               " WHERE id_location = :id_location";

    QSqlQuery query;
    query.prepare(strQuery);
    query.bindValue(":id_location", location->getId());
    return query.exec();
}

bool updateMoneyLocation(MoneyLocation* location, QString user_prefix)
{
    if (!location)
        return false;

    QString strQuery = " UPDATE ";
    strQuery = strQuery + user_prefix + "_location SET name = :name, description = :description "
               " WHERE id_location = :id_location";


    QSqlQuery query;
    query.prepare(strQuery);
    query.bindValue(":id_location", location->getId());
    query.bindValue(":name", location->getName());
    query.bindValue(":description", location->getDescription());
    return query.exec();
}

bool registerMoneyLocation(MoneyLocation* location, QString user_prefix)
{
    if (!location)
        return false;

    QString strQuery = " INSERT INTO ";
    strQuery = strQuery + user_prefix + "_location (name, description) values (:name, :description) ";

    QSqlQuery query;
    query.prepare(strQuery);
    query.bindValue(":name", location->getName());
    query.bindValue(":description", location->getDescription());
    return query.exec();
}
